#include <stdio.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <string.h>
#include <unistd.h>
#include "../twofish/myTwofish2.h"

int main(void)
{
	int flag;
	RSA * rsa;
	FILE * fp;
	char * pwd;
		
	if((fp = fopen("private.key", "wb"))==NULL)
	{
		fprintf(stderr,"Error opening file. Try again later.\n");
		return -1;
	}
	rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
	
	if (!PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, 0, "hola"))
	{
		fprintf(stderr, "Error generating private key.\n");
		return -1;
	}
	
	fclose(fp);
	
	do
	{
		flag = 0;
		pwd = getpass("Private Key Password: ");
		if(pwd == NULL || (strlen(pwd) < 4 || strlen(pwd) > 16))
		{
			flag = 1;
			fprintf(stderr,"Your password length is incorrect\nPlease enter a password between 4 and 16 characters\n");
		}
	}		
	while(flag);
	
	if(privateK_enc(pwd)==-1)
	{
			fprintf(stderr, "Error encrypting private key.\n");
			remove("private.key");
			return -1;
	}
	
	if((fp = fopen("public.key", "wb"))==NULL)
	{
			fprintf(stderr,"Error opening file. Try again later.\n");
			return -1;
	}	
	if (!PEM_write_RSAPublicKey(fp, rsa))
	{
		fprintf(stderr, "Error generating public key.\n");
		return -1;
	}
	
	fclose(fp);
	return 0;	
}
